package com.nuanshui.heatedloan.middleware.mongodb;

import com.nuanshui.framework.utils.ObjectUtil;
import com.nuanshui.heatedloan.pageable.Pager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.CriteriaDefinition;
import org.springframework.data.mongodb.core.query.Query;

import java.lang.reflect.ParameterizedType;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class BaseQueryRepository<T> {

    @Autowired
    private MongoTemplate mongoTemplate;

    public List<T> findListByPage(Pager<T> page) {
        return findListByPage(page);
    }

    public Pager<T> findAllListByPage(Pager<T> pager,T query)
    {
        Criteria criteria=BaseQueryRepository.createCriteria(query);

        pager.setSort(new Sort(Sort.Direction.DESC, "createdAt"));
        List<T> list = findListByPage(pager,criteria);
        pager.setData(list);

        pager.setSort(null);
        return pager;
    }


    public List<T> findListByPage(Pager<T> page, CriteriaDefinition... criteria) {
        Query query = new Query();

        for (CriteriaDefinition item: criteria) {
            if (item != null) {
                query.addCriteria(item);
            }
        }

        Class <T> entityClass = (Class <T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];

        long count=mongoTemplate.count(query,entityClass);
        page.setTotal((int)count);

        //query
        query.with(page.getSort());
        query.skip(page.getOffset()).limit(page.getPageSize());// 从skip开始,取多少条记录

        return mongoTemplate.find(query,entityClass);
    }

    public static Criteria createCriteria(Object queryObj)
    {
        Criteria criteria=null;

        if(queryObj==null)
            return criteria;

        Map<String, Object> map= ObjectUtil.createParamsByJson(queryObj);

        int i=0;
        Set<Map.Entry<String,Object>> entrySet=map.entrySet();
        for (Map.Entry<String,Object> item: entrySet) {
            if (i == 0) {
                criteria = Criteria.where(item.getKey()).is(item.getValue());
            } else {
                criteria.and(item.getKey()).is(item.getValue());
            }
        }
        return criteria;
    }
}
